﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.Model;
using FantastPlatform.Decision.IService;
using FantastPlatform.Decision.IModel;
using FantastPlatform.Decision.Model;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.Common;
using System.Configuration;
using System.Linq;
using System.Data.SqlClient;

namespace FantastPlatform.Decision.UI.Service
{
    public partial class DirectiveViewService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (LoginEmployee == null)
            {
                ReturnErrorMessage("登陆时间太长页面已失效，请重新登陆");
                return;
            }
            LoginEmployee = Session["User"] as Employee;
            string organization = GetUnitByPoliceCode(LoginEmployee.Code);
            IList<IDirective> directiveList = new List<IDirective>();
            IDirectiveService directiveService = ServiceFactory.CreateService<IDirectiveService>();
            string[] organizations = ConfigurationManager.AppSettings["DecOrganization"].Split(',');
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true, Comparison = Comparisons.Eq };
            group.Conditions.Add(enableCondition);
            int totalCount = 0;
            switch (Action)
            {
                case "Add":
                    string data = Data;
                    IDirective directive = (IDirective)JsonToEntity<Directive>(RepairString(data));
                    DirectiveView directiveView = (DirectiveView)JsonToEntity<DirectiveView>(RepairString(data));
                    if (directiveView.LeaderId != 0)
                        directive.Leader = new Employee() { Id = directiveView.LeaderId };
                    if (directive.StartTime != null || directive.EndTime != null)
                    {
                        if (directive.StartTime != null && directive.EndTime != null)
                        {
                            if (directive.StartTime >= directive.EndTime)
                            {
                                ReturnErrorMessage("开始时间不能大于结束时间");
                                return;
                            }
                            if (directive.StartTime.Value.AddHours(20) <= directive.EndTime)
                            {
                                ReturnErrorMessage("开始时间和结束时间不能相差20小时");
                                return;
                            }
                        }
                        else
                        {
                            ReturnErrorMessage("请填写完整的时间段");
                            return;
                        }
                    }

                    directiveService = ServiceFactory.CreateService<IDirectiveService>();
                    if (directive.Id == 0)
                    {
                        CreateNewDirective(directive);

                        directive.ModifyDate = DateTime.Now;
                        directiveService.Create(directive);
                        ReturnSuccessMessage("保存成功");
                    }
                    else
                    {
                        IDirective oldDirective = directiveService.Get(directive.Id);

                        if (oldDirective.ModifyDate == null)
                            CreateNewDirective(oldDirective);

                        oldDirective.Code = directive.Code;
                        oldDirective.Description = directive.Description;
                        oldDirective.Leader = directive.Leader;
                        oldDirective.Latitude = directive.Latitude;
                        oldDirective.Longitude = directive.Longitude;
                        oldDirective.LeaderTel = directive.LeaderTel;
                        oldDirective.Organization = directive.Organization;
                        oldDirective.OtherOrgPersonNum = directive.OtherOrgPersonNum;
                        oldDirective.OtherOrgPersons = directive.OtherOrgPersons;
                        oldDirective.SelfOrgPersonNum = directive.SelfOrgPersonNum;
                        oldDirective.SelfOrgPersons = directive.SelfOrgPersons;
                        oldDirective.StartTime = directive.StartTime;
                        oldDirective.EndTime = directive.EndTime;
                        oldDirective.Task = directive.Task;
                        oldDirective.Area = directive.Area;
                        directiveService.Update(oldDirective);
                        ReturnSuccessMessage("修改成功");
                    }

                    break;
                case "Search":
                    bool isAll = false;

                   // organization = LoginEmployee.EmployeePosts[0].Post.Organization.Name;
                    if (organization.Contains("责任区"))
                    {
                        organization = LoginEmployee.EmployeePosts[0].Post.Organization.Parent.Name;

                    }
                    for (int i = 0; i < organizations.Length; i++)
                    {
                        if (organization == organizations[i])
                        {
                            isAll = true;
                            break;
                        }
                    }
                    if (!isAll)
                        group.Conditions.Add(new Condition() { Type = typeof(string).FullName, Field = "Organization", Value1 = organization, Relation = Relations.And, Comparison = Comparisons.Eq });

                    group.Conditions.Add(new Condition() { Type = typeof(DateTime).FullName, Field = "EndTime", Value1 = DateTime.Now.Date, Relation = Relations.And, Comparison = Comparisons.Gt });
                    IList<Sort> sorts = new List<Sort>();

                    directiveList = directiveService.Search(group, sorts, PageSize, SelfPage, out totalCount);

                    var obj = from n in directiveList
                              orderby n.StartTime
                              select new
                              {
                                  Id = n.Id,
                                  Leader = n.Leader == null ? "" : n.Leader.Name,
                                  LeaderTel = n.LeaderTel,
                                  Description = n.Description,
                                  Organization = n.Organization,
                                  OtherOrgPersonNum = n.OtherOrgPersonNum,
                                  OtherOrgPersons = n.OtherOrgPersons,
                                  SelfOrgPersonNum = n.SelfOrgPersonNum,
                                  SelfOrgPersons = n.SelfOrgPersons,
                                  StartTime = n.StartTime == null ? "" : n.StartTime.ToString(),
                                  Task = n.Task,
                                  EndTime = n.EndTime == null ? "" : n.EndTime.ToString(),
                                  Area = n.Area,
                                  Longitude = n.Longitude,
                                  Latitude = n.Latitude,
                                  Code = n.Code
                              };
                    ReturnList(totalCount, obj.ToList());
                    break;
                case "SearchByCondition":
                    organization = LoginEmployee.EmployeePosts[0].Post.Organization.Name;
                    string Searchjson = RepairString(Data);
                    directive = JsonToEntity<Directive>(Searchjson);
                    isAll = false;
                    for (int i = 0; i < organizations.Length; i++)
                    {
                        if (organization == organizations[i])
                        {
                            isAll = true;
                            break;
                        }
                    }
                    if (!isAll)
                        directive.Organization = organization;

                    if (directive.StartTime != null)
                    {
                        group.Conditions.Add(new Condition() { Type = typeof(DateTime).FullName, Field = "EndTime", Value1 = directive.StartTime.Value.Date.AddDays(1), Relation = Relations.And, Comparison = Comparisons.Lt });
                    }
                    else
                    {
                        directive.StartTime = DateTime.Now;
                    }
                    group.Conditions.Add(new Condition() { Type = typeof(DateTime).FullName, Field = "EndTime", Value1 = directive.StartTime.Value.Date, Relation = Relations.And, Comparison = Comparisons.Gt });

                    if (!string.IsNullOrEmpty(directive.Organization))
                        group.Conditions.Add(new Condition() { Type = typeof(string).FullName, Field = "Organization", Value1 = directive.Organization, Relation = Relations.And, Comparison = Comparisons.Eq });

                    if (!string.IsNullOrEmpty(directive.Code))
                        group.Conditions.Add(new Condition() { Type = typeof(string).FullName, Field = "Code", Value1 = directive.Code, Relation = Relations.And, Comparison = Comparisons.Eq });

                    sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "StartTime", Order = Orders.Asc });
                    directiveList = directiveService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    obj = from n in directiveList
                          orderby n.StartTime
                          select new
                          {
                              Id = n.Id,
                              Leader = n.Leader == null ? "" : n.Leader.Name,
                              LeaderTel = n.LeaderTel,
                              Description = n.Description,
                              Organization = n.Organization,
                              OtherOrgPersonNum = n.OtherOrgPersonNum,
                              OtherOrgPersons = n.OtherOrgPersons,
                              SelfOrgPersonNum = n.SelfOrgPersonNum,
                              SelfOrgPersons = n.SelfOrgPersons,
                              StartTime = n.StartTime == null ? "" : n.StartTime.ToString(),
                              Task = n.Task,
                              EndTime = n.EndTime == null ? "" : n.EndTime.ToString(),
                              Area = n.Area,
                              Longitude = n.Longitude,
                              Latitude = n.Latitude,
                              Code = n.Code
                          };
                    ReturnList(totalCount, obj.ToList());
                    break;
                case "Get":
                    directive = directiveService.Get(Id);
                    object objDirective = (new
                                     {
                                         Id = directive.Id,
                                         Name = directive.Leader == null ? "" : directive.Leader.Id.ToString() + "|" + directive.Leader.Name,
                                         LeaderTel = directive.LeaderTel,
                                         Description = directive.Description,
                                         Organization = directive.Organization,
                                         OtherOrgPersonNum = directive.OtherOrgPersonNum,
                                         OtherOrgPersons = directive.OtherOrgPersons,
                                         SelfOrgPersonNum = directive.SelfOrgPersonNum,
                                         SelfOrgPersons = directive.SelfOrgPersons,
                                         StartTime = directive.StartTime,
                                         Task = directive.Task,
                                         EndTime = directive.EndTime,
                                         Area = directive.Area,
                                         Longitude = directive.Longitude,
                                         Latitude = directive.Latitude,
                                         Code = directive.Code
                                     });
                    ReturnObj2(objDirective);
                    break;
                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    directiveService.Delete(idList);
                    ReturnSuccessMessage("删除会议成功");
                    break;
                case "GetOrganization":
                    isAll = false;

                   // organization = LoginEmployee.EmployeePosts[0].Post.Organization.Name;
                    for (int i = 0; i < organizations.Length; i++)
                    {
                        if (organization == organizations[i])
                        {
                            isAll = true;
                            break;
                        }
                    }

                    IOrganizationService orgService = ServiceFactory.CreateService<IOrganizationService>();
                    totalCount = 0;
                    IList<IOrganization> orgList = new List<IOrganization>();
                    if (isAll)
                    {
                        group.Conditions.Add(new Condition() { Field = "Parent.Id", Type = typeof(Int32).FullName, Value1 = "1", Comparison = Comparisons.Like, Relation = Relations.And });
                        orgList = orgService.Search(group, null, int.MaxValue, 1, out totalCount);
                    }
                    else
                    {
                        if (organization.Contains("责任区"))
                        {
                            orgList.Add(LoginEmployee.EmployeePosts[0].Post.Organization.Parent);

                        }
                        else
                        {
                            orgList.Add(LoginEmployee.EmployeePosts[0].Post.Organization);
                        }
                    }
                    object[] orgObjs = (from emp in orgList
                                        select new
                                        {
                                            Id = emp.Id,
                                            Name = emp.Name,
                                            Code = emp.Code
                                        }).ToArray();
                    ReturnList(orgObjs.Count(), orgObjs);
                    break;
                case "SearchPoliceByStation":
                    string code = "";
                    if (!string.IsNullOrEmpty(Request["code"]))
                    {
                        code = Request["code"];
                    }

                    totalCount = 0;
                    Condition condition = new Condition();
                    if (!string.IsNullOrEmpty(code))
                    {

                        if (Tools.IsChinese(code))
                        {
                            condition = new Condition() { Field = "Name", Type = typeof(string).FullName, Value1 = code + "%", Comparison = Comparisons.Like };

                        }
                        else
                            condition = new Condition() { Field = "Code", Type = typeof(string).FullName, Value1 = code + "%", Comparison = Comparisons.Like };
                        group.Conditions.Add(condition);
                    }
                    IList<IEmployee> empList = new List<IEmployee>();
                    IEmployeeService employeeService = ServiceFactory.CreateService<IEmployeeService>();
                    empList = employeeService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] objArr = (from o in empList
                                       select new
                                       {
                                           Id = o.Id,
                                           Code = o.Code,
                                           Name = o.Name
                                       }
                                    ).ToArray();
                    ReturnList(totalCount, objArr);
                    break;
            }
        }

        private string GetUnitByPoliceCode(string p)
        {
            string sql = "select o.name from policeManager2.dbo.Org_Organization as o inner join [case].dbo.[user] as u on o.code = u.unitcode where u.Number = '" + p + "'";
            string organization = "";
            string conStr = ConfigurationManager.AppSettings["Case"];
            try
            {
                SqlConnection con = new SqlConnection(conStr);
                SqlCommand command = new SqlCommand(sql, con);
                con.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    organization = reader[0].ToString();
                }
            }
            catch (Exception ex)
            {

            }
            return organization;
        }

        private void CreateNewDirective(IDirective directive)
        {
            IDirectiveService directiveService = ServiceFactory.CreateService<IDirectiveService>();

            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true, Comparison = Comparisons.Eq };
            group.Conditions.Add(enableCondition);
            int totalCount = 0;

            IDirective newdirective = new Directive();
            newdirective.Code = directive.Code;
            newdirective.Name = directive.Name;
            newdirective.Latitude = directive.Latitude;
            newdirective.Longitude = directive.Longitude;
            newdirective.Organization = directive.Organization;
            newdirective.Description = directive.Description;
            newdirective.StartTime = directive.StartTime.Value.AddDays(1);
            newdirective.EndTime = directive.EndTime.Value.AddDays(1);
            newdirective.Task = directive.Task;
            newdirective.Area = directive.Area;

            group.Conditions.Add(new Condition() { Type = typeof(string).FullName, Field = "Organization", Value1 = newdirective.Organization, Relation = Relations.And, Comparison = Comparisons.Eq });
            group.Conditions.Add(new Condition() { Type = typeof(string).FullName, Field = "Description", Value1 = newdirective.Description, Relation = Relations.And, Comparison = Comparisons.Eq });
            group.Conditions.Add(new Condition() { Type = typeof(DateTime).FullName, Field = "StartTime", Value1 = newdirective.StartTime, Relation = Relations.And, Comparison = Comparisons.Eq });
            IList<IDirective> directiveList = directiveService.Search(group, null, PageSize, SelfPage, out totalCount);
            if (directiveList.Count == 0)
                directiveService.Create(newdirective);

        }

        public class DirectiveView
        {
            public string Code
            {
                get;
                set;
            }
            public string Description
            {
                get;
                set;
            }
            public string Organization
            {
                get;
                set;
            }

            public DateTime? StartTime
            {
                get;
                set;
            }

            public DateTime? EndTime
            {
                get;
                set;
            }

            public int LeaderId
            {
                get;
                set;
            }

            public string LeaderTel
            {
                get;
                set;
            }

            public string Area
            {
                get;
                set;
            }

            public string Task
            {
                get;
                set;
            }

            public string SelfOrgPersons
            {
                get;
                set;
            }

            public int SelfOrgPersonNum
            {
                get;
                set;
            }

            public string OtherOrgPersons
            {
                get;
                set;
            }

            public int OtherOrgPersonNum
            {
                get;
                set;
            }
            public string Latitude
            {
                get;
                set;
            }
            public string Longitude
            {
                get;
                set;
            }

        }
    }
}